package com.crazy.sso.website.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.SSOToken;
import com.baomidou.kisso.annotation.Action;
import com.baomidou.kisso.annotation.Login;
import com.baomidou.kisso.common.util.HttpUtil;
import com.baomidou.kisso.web.waf.request.WafRequestWrapper;
import com.crazy.shell.api.users.UsersProvider;
import com.crazy.shell.common.controller.BaseController;
import com.crazy.shell.common.result.ActionResult;
import com.crazy.shell.dao.entity.Users;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Created by creazier.huang on 16/4/17.
 */
@Controller
public class LoginController extends BaseController {

    @Value("${reg.url}")
    private String regUrl;

    @Reference
    private UsersProvider usersProvider;

    @Login(action = Action.Skip)
    @RequestMapping("/login.htm")
    public String login(ModelMap model){
        model.put("layout", "/layout/empty.vm");
        SSOToken st = SSOHelper.getToken(request);
        String returnUrl = request.getParameter("ReturnURL");
        if(st!=null){
            return redirectTo(returnUrl);
        }

        model.put("regUrl",regUrl);
        if(!StringUtils.isEmpty(returnUrl)) model.put("ReturnURL",returnUrl);

        return "/login/login";
    }


    /**
     * 登录 （注解跳过权限验证）
     */
    @Login(action = Action.Skip)
    @RequestMapping("/loginpost.htm")
    public String loginpost() {
        /**
         * 生产环境需要过滤sql注入
         */
        WafRequestWrapper req = new WafRequestWrapper(request);
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String ReturnURL = req.getParameter("ReturnURL");

        Users conf = new Users();
        conf.setUsername(username);
        conf.setPassword(password);
        ActionResult result  = usersProvider.getByObj(conf);
        if(result.getSuccess()){
            Users users = (Users) result.getAttachs().get("data");
            SSOToken st = new SSOToken(request);
            st.setId(Long.valueOf(users.getId()));
            st.setUid(String.valueOf(users.getId()));
            st.setType(1);

            //记住密码，设置 cookie 时长 1 周 = 604800 秒 【动态设置 maxAge 实现记住密码功能】
            //String rememberMe = req.getParameter("rememberMe");
            //if ( "on".equals(rememberMe) ) {
            //	request.setAttribute(SSOConfig.SSO_COOKIE_MAXAGE, 604800);
            //}
            SSOHelper.setSSOCookie(request,response,st,true);
            String returnUrl = HttpUtil.decodeURL(ReturnURL);
            if(!StringUtils.isEmpty(ReturnURL))return redirectTo(returnUrl);
            return redirectTo("/index.htm");

        }


        return "login";
    }
}
